<?php
/**
 * Created by PhpStorm.
 * User: xing.chen
 * Date: 2018/6/2
 * Time: 21:16
 */

namespace apps\api\modules\user\controllers;


use common\map\CommonMap;
use common\modules\user\logic\UserFollowLogic;
use common\modules\user\map\UserMap;
use common\modules\user\UserFollow;
use Yii;

class UserFollowController extends \apps\api\modules\ApiBaseController
{

    public $modelClass = 'common\modules\user\UserFollow';

    public function actionIndex($page)
    {
        try {
            $list = UserFollow::getModel($page)
                ->where(['followUserId' => $this->userId])
                ->with(['user' => function ($q) {$q->select(UserMap::$baseField);}])
                ->asArray()
                ->all();
            // 全部设置为已读
            $where = ['isRead' => CommonMap::BOOLEAN_NO, 'followUserId' => $this->userId];
            UserFollow::updateAll(['isRead' => CommonMap::BOOLEAN_YES], $where);
            return $this->returnList($list);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionMy($page)
    {
        try {
            $list = UserFollow::getModel($page)
                ->where(['userId' => $this->userId])
                ->with(['user' => function ($q) {$q->select(UserMap::$baseField);}])
                ->asArray()
                ->all();
            return $this->returnList($list);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionCreate($userId)
    {
        try {
            $data = UserFollowLogic::create($this->userId, $userId);
            return $this->returnData($data);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionAuto()
    {
        try {
            $follow = UserFollow::readInfo($this->userId, Yii::$app->request->post('userId'));
            return $follow ? $this->actionCancel() : $this->actionCreate();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }


    public function actionDelete($userId)
    {
        try {
            UserFollow::cancel($this->userId, $userId);
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }
}